import python_jwt as jwt, jwcrypto.jwk as jwk ,datetime
import time
'''
iss:签发人
sub：主题
aud:用户
iat:时间
jti:token标识
exp：过期时间
nbf：在此之前不可用
'''

tokenKey=jwk.JWK.generate(kty='RSA',size=2048)
def generateToken(payload):
    #token有效时间为两天,测试时为2分钟
    #token=jwt.generate_jwt(payload,tokenKey,'PS256',datetime.timedelta(days=2))
    token = jwt.generate_jwt(payload, tokenKey, 'PS256', datetime.timedelta(minutes=2))
    print(token)
    return token

def verifyToken(token):
    try:
        header, claims = jwt.verify_jwt(token, tokenKey, ['PS256'])
        print('接收到的token',claims)
        return True
    except jwt._JWTError as e:
        print("token过期")
        return False

def updateTokey(token):
    header, claims = jwt.verify_jwt(token, tokenKey, ['PS256'])
    claims.pop('exp')
    token = jwt.generate_jwt(claims, tokenKey, 'PS256', datetime.timedelta(minutes=2))
    header, claims = jwt.verify_jwt(token, tokenKey, ['PS256'])
    return token

if __name__=="__main__":
    token=generateToken({'username':'shensy','role':'M',})
    verifyToken(token)
    time.sleep(1)
    token=updateTokey(token)
    verifyToken(token)
    time.sleep(3)
    verifyToken(token)